package com.zzw.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import sun.misc.BASE64Encoder;

public class Utility {
	public static boolean isEmpty(String s) {
		if (s == null || s.trim().isEmpty() || "null".equals(s)) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isEmptyObj(Object obj) {
		if (obj == null)
			return true;

		String s = obj.toString();
		if (s.trim().isEmpty() || "null".equals(s)) {
			return true;
		} else {
			return false;
		}
	}

	public static String trimObj(Object obj) {
		if (obj == null) {
			return null;
		} else {
			return obj.toString().trim();
		}
	}
	
	public static String nullClearObj(String obj){
		if(Utility.isEmpty(obj)){
			return null;
		}else{
			return Utility.trimObj(obj);
		}
	}

	public static String nullObj(String obj) {
		if (obj == null) {
			return "";
		}
		return obj.trim();
	}

	public static boolean isEmail(String email) {
		Pattern p = Pattern
				.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
		Matcher m = p.matcher(email);
		return m.matches();
	}

	public static boolean isMobileDevice(String requestHeader) {
		/**
		 * android : 所有android设备 mac os : iphone ipad windows
		 * phone:Nokia等windows系统的手机
		 */
		String[] deviceArray = new String[] { "android", "mac os",
				"windows phone" };
		if (requestHeader == null)
			return false;
		requestHeader = requestHeader.toLowerCase();
		for (int i = 0; i < deviceArray.length; i++) {
			if (requestHeader.indexOf(deviceArray[i]) > 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取指定格式的当前时间
	 * 
	 * @param format
	 *            时间格式
	 * @return 返回指定格式的当前时间
	 */
	public static Timestamp getCurrentTimestamp(String format) {
		if (Utility.isEmpty(format)) {
			format = "yyyy-MM-dd HH:mm:ss";
		}
		// 获取格式化日期类
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String dateStr = getCurrentTimestampStr(format);
		// 创建Date对象
		Date date = null;
		try {
			// 将dateStr转换成指定格式的时间
			date = sdf.parse(dateStr);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		// 生成Timestamp
		Timestamp ts = new Timestamp(date.getTime());
		return ts;
	}

	/**
	 * 获取指定格式的当前时间字符串
	 * 
	 * @param format
	 *            时间格式
	 * @return 返回指定格式的当前时间字符串
	 */
	public static String getCurrentTimestampStr(String format) {
		if (format == null) {
			format = "yyyy-MM-dd HH:mm:ss";
		}
		// 获取当前时间
		Timestamp currentDate = new Timestamp(System.currentTimeMillis());
		// 获取格式化日期类
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		// 获取当前时间的字符串格式
		String dateStr = sdf.format(currentDate);
		return dateStr;
	}

	public static String getTimestampStr(Timestamp ts, String format) {
		if (ts == null) {
			return null;
		}
		if (format == null) {
			format = "yyyy-MM-dd";
		}
		// 获取格式化日期类
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		// 获取当前时间的字符串格式
		String dateStr = sdf.format(ts);
		return dateStr;
	}

	public static Timestamp getStringTimestamp(String dateStr, String format) {
		if (Utility.isEmpty(dateStr)) {
			return null;
		}
		if (Utility.isEmpty(format)) {
			format = "yyyy-MM-dd";
		}
		// 获取格式化日期类
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		// 创建Date对象
		Date date = null;
		try {
			// 将dateStr转换成指定格式的时间
			date = sdf.parse(dateStr);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		// 生成Timestamp
		Timestamp ts = new Timestamp(date.getTime());
		return ts;
	}

	/**
	 * 检查是否为整数
	 * 
	 * @param str
	 *            待检查字符串
	 * @return 整数 true 其他 false
	 */
	public static boolean isInteger(String str) {
		if (Utility.isEmpty(str)) {
			return false;
		} else {
			return str.matches("^-?\\d+$");
		}
	}

	/**
	 * 判断是否为日期类型 yyyy-MM-dd HH:mm:ss格式
	 * 
	 * @param date
	 * @return
	 */
	@SuppressWarnings("unused")
	public static boolean isDate(String date, String type) {
		/**
		 * 判断日期格式和范围
		 */

		// Pattern pat =
		// Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s((([0-1][0-9])|(2?[0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
		Pattern pat = null;
		String compile = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s((([0-1][0-9])|(2?[0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
		if ("yyyy-MM-dd HH:mm".equals(type)) {
			pat = Pattern
					.compile("^[1-2][0-9][0-9][0-9]-([1][0-2]|0?[1-9])-([12][0-9]|3[01]|0?[1-9]) ([01]?[0-9]|[2][0-3]):[0-5]?[0-9]$");
		} else if ("MM/dd/YY".equals(type)) {
			pat = Pattern
					.compile("^(?:(?:(?:0?[1-9]|1[0-9]|2[0-8])([-/.]?)(?:0?[1-9]|1[0-2])|(?:29|30)([-/.]?)(?:0?[13-9]|1[0-2])|31([-/.]?)(?:0?[13578]|1[02]))([-/.]?)(?!0000)[0-9]{4}|29([-/.]?)0?2([-/.]?)(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00))$");
		} else {
			pat = Pattern
					.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s((([0-1][0-9])|(2?[0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
		}
		if (pat == null) {
			return false;
		}
		Matcher mat = pat.matcher(date);
		return mat.matches();
	}

	/**
	 * 利用MD5进行加密
	 * 
	 * @param str
	 *            待加密的字符串
	 * @return 加密后的字符串
	 * @throws NoSuchAlgorithmException
	 *             没有这种产生消息摘要的算法
	 * @throws UnsupportedEncodingException
	 */
	public static String encoderByMd5(String str)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		// 确定计算方法
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		BASE64Encoder base64en = new BASE64Encoder();
		// 加密后的字符串
		String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
		return newstr;
	}

	/**
	 * 提取html中的文本信息
	 * 
	 * @param html
	 *            html信息
	 * @param length
	 *            截取的长度
	 * @return 返回截取后的字符串
	 */
	public static String getHtmlText(String html, int length) {
		Pattern pattern = Pattern.compile("\\<.[^\\<]*\\>");
		Matcher matcher = pattern.matcher(html);
		String text = matcher.replaceAll("");
		if (text != null) {
			text = text.replace("&nbsp;", "");
		}
		return getTextSubLength(text, length);
	}

	public static String getHtmlText(String html) {
		return getHtmlText(html, -1);
	}

	public static String getStringTel(String fromText, boolean isFirst) {
		Pattern pattern = Pattern
				.compile("(?<!\\d)(?:(?:1[358]\\d{9})|(?:861[358]\\d{9}))(?!\\d)");
		Matcher matcher = pattern.matcher(fromText);
		StringBuffer bf = new StringBuffer();
		while (matcher.find()) {
			if (isFirst) {
				return matcher.group();
			}
			bf.append(matcher.group()).append(",");
		}
		int len = bf.length();
		if (len > 0) {
			bf.deleteCharAt(len - 1);
		}
		return bf.toString();
	}

	public static String getTextSubLength(String text, int length) {
		if (length == -1) {
			return text;
		}
		if (length < text.length()) {
			text = text.substring(0, length) + "...";
		}
		return text;
	}

	public static String getNextId(Object id, int length) {
		if (id != null) {
			return ((Long.parseLong("1" + id) + 1) + "").substring(1);
		} else {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < length - 1; i++) {
				sb.append("0");
			}
			sb.append("1");
			return sb.toString();
		}
	}

	public static String getNextId(String pre, Object id, int length) {
		if (id != null) {
			String idStr = id.toString();
			String subNum = idStr.substring(idStr.indexOf(pre) + pre.length());
			if (Utility.isInteger(subNum)) {
				return pre
						+ ((Long.parseLong("1" + subNum) + 1) + "")
								.substring(1);
			}
		}
		StringBuffer sb = new StringBuffer(pre);
		for (int i = 0; i < length - 1; i++) {
			sb.append("0");
		}
		sb.append("1");
		return sb.toString();

	}

	public static String getSixStr() {
		Random random = new Random();
		char f1 = (char) (random.nextInt(25) + 97);
		int i1 = random.nextInt(9);
		char f2 = (char) (random.nextInt(25) + 97);
		int i2 = random.nextInt(9);
		char f3 = (char) (random.nextInt(25) + 97);
		int i3 = random.nextInt(9);
		String newPwd = "" + f1 + i1 + f2 + i2 + f3 + i3;
		return newPwd;
	}

	public static String getNums(int nums) {
		Random random = new Random();
		String str = "";
		for (int i = 0; i < nums; i++) {
			str = str + random.nextInt(9);
		}
		return str;
	}

	public static String makeJSONString(Object data)
			throws JsonGenerationException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		if (data == null) {
			return "";
		} else if (data instanceof String) {
			return data.toString();
		} else {
			return mapper.writeValueAsString(data);
		}
	}
	
	public static String getHttpGetParam(String old){
		try {
			return new String(old.getBytes("iso-8859-1"),"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
